import axios from "axios";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { getLocalCache, getLocalJsonCache, setLocalJsonCache } from "@/utils/cache";
import { microAppMainRouter } from "@/microApp";
import globalConfig from "@/settings";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
});

service.interceptors.request.use(
  config => {
    const isFormData = config.data instanceof FormData;
    const isToken = (config.headers || {}).isToken === false;
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;
    config?.scope && (config.headers.scope = config.scope);
    isFormData && (config.headers["Content-Type"] = "multipart/form-data");
    if (getLocalCache(globalConfig.tokenAttr) && !isToken) {
      config.headers["Authorization"] = "Bearer " + getLocalCache(globalConfig.tokenAttr);
    }
    if (!isRepeatSubmit && (config.method === "post" || config.method === "put")) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === "object" ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      };
      const sessionObj = getLocalJsonCache("sessionObj");
      if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
        setLocalJsonCache("sessionObj", requestObj);
      }
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  res => {
    const { code = 500 } = res.data;
    const msg = res.data?.msg || "服务器异常!!!";
    if (["blob", "arraybuffer"].includes(res.request.responseType)) {
      return res.data;
    }
    if (code === 401) {
      loginOverdue();
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    } else if (code === 500) {
      ElMessage({ message: msg, type: "error" });
      return Promise.reject(new Error(msg));
    } else if (code === 601) {
      ElMessage({ message: msg, type: "warning" });
      return Promise.reject(new Error(msg));
    } else if (code !== 200) {
      ElNotification.error({ title: msg });
      return Promise.reject(msg);
    } else {
      return Promise.resolve(res.data);
    }
  },
  error => {
    console.log(error, ">>>>");
    const { message = "请求超时" } = error;
    ElMessage({ message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

const loginOverdue = () => {
  ElMessageBox.confirm("登录状态已过期，您可以继续留在该页面，或者重新登录", "系统提示", {
    confirmButtonText: "重新登录",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      microAppMainRouter("replace", { path: "/login" });
    })
    .catch(err => {
      console.log(err);
    });
};

export default service;
